package BluetoothFileMgr.start;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothServer extends Thread{

	public BluetoothServerSocket mmServerSocket=null;
	TextView tv;
	public Context context;
	BluetoothAdapter adap;
	public void showMsg(String msg,Context context)
	{
		CharSequence text = msg;
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
	}
	
	public BluetoothServerSocket getSocket()
	{
		return mmServerSocket;
	}

	
	Handler handler = new Handler() {
  	  public void handleMessage(Message msg) {
  		tv.append("\n"+msg.obj.toString());
  		  //showMsg(msg.obj.toString(),context);
  	  
  	     }
  	 };
  	 
	public BluetoothServer(BluetoothAdapter adap,final Context context,TextView tv)
	{
		this.adap=adap;
		this.tv=tv;
		this.context=context;
		BluetoothServerSocket tmp = null;
		UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	        try
	        {
	            tmp = adap.listenUsingRfcommWithServiceRecord("", uuid);
	            //showMsg("Server Socket created",context);
	        } 
	        catch (IOException e) 
	        { 	
	        	showMsg("Cannot Create Server Socket",context);
	        }
	        mmServerSocket = tmp;
	 
	}
	
	public void run()
	{
		
		BluetoothSocket socket = null;
    	
    	// Keep listening until exception occurs or a socket is returned
		//while (true) 
		{
			try
    		{	Message msg = handler.obtainMessage();
    			msg.obj = "Turn On";
    			handler.sendMessage(msg);
    		}
    		catch (Exception e)
    		{	Message msg = handler.obtainMessage();
    			msg.obj = e.getMessage();
    			handler.sendMessage(msg);
    		}
			//msg.obj="Turned on";
			//handler.sendMessage(msg);
			try
			{
				socket = mmServerSocket.accept();
			}
			catch (IOException e) 
			{
				//msg.obj=e.getMessage();
				//handler.sendMessage(msg);
				//break;
			}
				if (socket != null)
				{
					try
            		{	Message msg = handler.obtainMessage();
            			msg.obj = "Connected";
            			handler.sendMessage(msg);
            		}
            		catch (Exception e)
            		{	Message msg = handler.obtainMessage();
            			msg.obj = "in catch of Connected";
            			handler.sendMessage(msg);
            		}
		    		
					
///////////////////////////////////////////////////////////////////////////////////////////////////
		    		/*
					try {
						OutputStream out=socket.getOutputStream();
						//byte[] b1=new byte[1024];
						//String str="Hello Lappy";
						//b1=str.getBytes();
						//out.write(b1);
						
						DataInputStream in=new DataInputStream(socket.getInputStream());
						String str1=in.readUTF();
						msg.obj=str1;
						handler.sendMessage(msg);
						
						//tv.append("\n"+str);
						
					out.close();	
					} catch (IOException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
		    		//String rcvd="";
		    		//msg.obj="Sending...";
		    		//handler.sendMessage(msg);
					
					*/
			    	
/////////////////////////////////////////////////////////////////////////////////////////////////////////
	    			
	    			String directory=Environment.getExternalStorageDirectory().toString();
	    			DataOutputStream out=null;
	    			DataInputStream in=null;
	    			try
	    			{
	    				out=new DataOutputStream(socket.getOutputStream());
	    				in=new DataInputStream(socket.getInputStream());
	    			}
	    			catch(Exception e)
	    			{
	    				Log.d(null, e.getMessage());
	    			}
	    			
		    		String rcvd="";
		    		
		    		while(true)
		    		{
		    			File f=new File(directory);
		    			String str=directory;
		    			if(f.list().length==0)
		    			{
		    				str+="!!empty!";
		    			}
		    			else
		    			{
		    				for(File file:f.listFiles())
		    				{
		    					if(file.isDirectory())
		    						str+="!!dir!"+file.getName()+"!"+file.length();
		    					else
		    						str+="!!file!"+file.getName()+"!"+file.length();
		    				}
		    			}
		    			try
		    			{
		    				out.writeUTF(str);
		    				rcvd=in.readUTF();
		    			}
		    			catch(Exception e)
		    			{
		    				
		    			}
		    			try{
		    				Message msg=handler.obtainMessage();
		    				msg.obj=rcvd;
		    				handler.sendMessage(msg);
		    			}
		    			catch(Exception e)
		    			{
		    				Message msg=handler.obtainMessage();
		    				msg.obj=e.getMessage();
		    				handler.sendMessage(msg);
		    			}
			    		String[] sArr=rcvd.split("!!");
			    		if(sArr[0].equals("GOTO"))
			    		{
			    			directory=directory+"/"+sArr[1];
			    		}
			    		else if(sArr[0].equals("BACK"))
			    		{
			    			if(!directory.equals("/mnt"))
			    			{
			    				String[] sA=directory.split("/");
			    				directory="";
			    				int j=1;
			    				while(j<sA.length-1)
			    				{
			    					directory=directory+"/"+sA[j];
			    					j++;
			    				}
			    			}
			    		}
			    		else if(sArr[0].equals("ADD"))
			    		{
			    			String lastDir=directory;
			    			directory+="/"+sArr[1];
			    			File fNew=new File(directory); 
			    			fNew.mkdir();
			    			directory=lastDir;
			    		}
			    		else if(sArr[0].equals("DOWNLOAD"))
			    		{
			    			FileInputStream f2send=null;
    						
			    			
			    			////////////////////////////////////////////
			    			//RunFile abc=new RunFile(directory+"/"+sArr[1]);
			    			//while(true)
			    			//{
			    			////////////////////////////////////////////
			    			 
			    			try 
			    			{/*
			    				BluetoothServerSocket tmp = null;
			    				UUID uuid=UUID.fromString("00001101-0000-1000-8000-00805F9B34FC");
			    			        try
			    			        {
			    			            tmp = adap.listenUsingRfcommWithServiceRecord("", uuid);
			    			            //showMsg("Server Socket created",context);
			    			        } 
			    			        catch (IOException e) 
			    			        { 	
			    			        	showMsg("Cannot Create Server Socket",context);
			    			        }
			    				BluetoothSocket fileSocket=tmp.accept();*/
				    			//OutputStream send;
				    			try
			            		{	Message msg = handler.obtainMessage();
			            			msg.obj = "Sending...";
			            			handler.sendMessage(msg);
			            		}
			            		catch (Exception e)
			            		{	Message msg = handler.obtainMessage();
			            			msg.obj = "in catch of Sending";
			            			handler.sendMessage(msg);
			            		}
								//msg.obj="Sending...";
								//handler.sendMessage(msg);
				    			//if (socket != null)
								{
				    				byte[] b=null;
		    						try 
		    						{
		    							File f1=new File(directory+"/"+sArr[1]);
		   								f2send = new FileInputStream(f1);
		   								try
					            		{	Message msg = handler.obtainMessage();
					            			msg.obj = "File Read: "+f1.length();
					            			handler.sendMessage(msg);
					            		}
					            		catch (Exception e)
					            		{	Message msg = handler.obtainMessage();
					            			msg.obj = e.getMessage();
					            			handler.sendMessage(msg);
					            		}
										b=new byte[(int) f1.length()];
										f2send.read(b);
										//send = fileSocket.getOutputStream();
										//send=socket.getOutputStream();
					    				out.write(b);
					    				f2send.close();
					    				//send.close();
										
									} 
									catch (IOException e) 
									{
										
									}
				    				
				    				//send.close();
								}
				    			try
			            		{	
				    				Message msg = handler.obtainMessage();
			            			msg.obj = "Sent";
			            			handler.sendMessage(msg);
			            		}
			            		catch (Exception e)
			            		{	Message msg = handler.obtainMessage();
			            			msg.obj = e.getMessage();
			            			handler.sendMessage(msg);
			            		}
		    					//fileSocket.close();
		    					//msg.obj="Sent";
								//handler.sendMessage(msg);
							}
			    			catch (Exception e) 
			    			{
			    				Message msg = handler.obtainMessage();
		            			msg.obj = e.getMessage();
		            			handler.sendMessage(msg);
								//msg.obj=e.getMessage();
								//handler.sendMessage(msg);
							}
							
							//////////////////////////////////////////////
			    			//msg.obj="Sending "+directory+"/"+sArr[1]+"...";
				    		//handler.sendMessage(msg);
			    			
			    			//DataOutputStream send=new DataOutputStream(fileSocket.getOutputStream());
			    			
			    			//DataInputStream f2send=new DataInputStream(new FileInputStream(directory+"/"+sArr[1]));
			    			//String s=f2send.readUTF();
			    			//send.writeUTF(s);
			    			//
			    			//////////////////////////////////////////////
			    			
			    			
			    		}
			    		else if (sArr[0].equals("DELETE"))
		    			{
		    				for(File f1 : f.listFiles())
		    				{
		    					if(f1.getName().equals(sArr[1]))
		    					{
		    						f1.delete();
		    					}
		    				}
		    			}
			    		else if (sArr[0].equals("RENAME"))
		    			{
		    				for(File f1 : f.listFiles())
		    				{
		    					if(f1.getName().equals(sArr[1]))
		    					{
		    						f1.renameTo(new File(directory+"/"+sArr[2]));
		    					}
		    				}
		    			}
			    		try
	            		{	Message msg = handler.obtainMessage();
	            			msg.obj = directory;
	            			handler.sendMessage(msg);
	            		}
	            		catch (Exception e)
	            		{	Message msg = handler.obtainMessage();
	            			msg.obj = e.getMessage();
	            			handler.sendMessage(msg);
	            		}
			    		//msg.obj=directory;
		    			//handler.sendMessage(msg);
		    		}//while(true) file share
		    		//out.close();    
		    		//socket.close();
				}
				//mmServerSocket.close();	
			
		}//while(true) socket
        // If a connection was accepted
       }
	
	  /*public void cancel() {
	        try {
	            mmServerSocket.close();
	        } catch (IOException e) { }
	    }*/
}
